package com.longcai.cm.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.longcai.cm.base.service.BaseServiceImpl;
import com.longcai.cm.dao.JaVipInfoMapper;
import com.longcai.cm.domain.JaCoupon;
import com.longcai.cm.domain.JaMemberCoupons;
import com.longcai.cm.domain.JaMemberVip;
import com.longcai.cm.domain.JaVipInfo;
import com.longcai.cm.domain.vm.MemberVipViewModel;
import com.longcai.cm.service.JaCouponService;
import com.longcai.cm.service.JaMemberCouponsService;
import com.longcai.cm.service.JaMemberVipService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author LBX
 */
@Service
public class JaMemberVipServiceImpl extends BaseServiceImpl<JaMemberVip> implements JaMemberVipService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private JaVipInfoMapper vipInfoMapper;

    @Resource
    private JaCouponService couponService;

    @Resource
    private JaMemberCouponsService memberCouponsService;

    /**
     * 查询是否VIP
     *
     * @param memberId 用户id
     * @return true/false
     */
    @Override
    public Boolean isVip(Integer memberId) {
        return getVipInfo(memberId).getIfVip() == 1;
    }

    /**
     * VIP详情
     *
     * @param memberId 用户id
     * @return MemberVipViewModel
     */
    @Override
    public MemberVipViewModel getVipInfo(Integer memberId) {
        final MemberVipViewModel viewModel = new MemberVipViewModel();
        final JaMemberVip one = lambdaQuery().eq(JaMemberVip::getMemberId, memberId).one();
        if (one == null) {
            viewModel.setIfVip(0);
            viewModel.setVipInfo(vipInfoMapper.selectOne(new LambdaQueryWrapper<JaVipInfo>().eq(JaVipInfo::getLevel, 1)));
            return viewModel;
        }
        viewModel.setIfVip(DateUtil.parse(one.getExpireTime()).after(DateUtil.date()) ? 1 : 2);
        viewModel.setVipInfo(vipInfoMapper.selectOne(
                new LambdaQueryWrapper<JaVipInfo>()
                        .eq(JaVipInfo::getLevel, 2)
                        .last(" limit 1 ")
        ));
        viewModel.setMemberVipId(one.getId());
        viewModel.setCreateTime(one.getCreateTime());
        viewModel.setExpireTime(one.getExpireTime());
        viewModel.setLevel(one.getLevel());
        return viewModel;
    }

    /**
     * @param vipId    会员
     * @param memberId 用户
     */
    @Override
    public void addVip(String vipId, Integer memberId) {
        final JaVipInfo vip = vipInfoMapper.selectById(vipId);
        if (vip == null) {
            return;
        }
        final MemberVipViewModel vipInfo = getVipInfo(memberId);
        DateTime expireTime;
//        是否VIP 0未开通 1是 2已过期
        if (vipInfo.getIfVip() == 1) {
            DateTime time = DateUtil.parse(vipInfo.getExpireTime());
            expireTime = time.offset(DateField.DAY_OF_YEAR, vip.getAvailableMonth());
            lambdaUpdate().eq(JaMemberVip::getMemberId, memberId)
                    .set(JaMemberVip::getExpireTime, expireTime)
                    .set(JaMemberVip::getLevel, vip.getLevel())
                    .set(JaMemberVip::getVipInfoId, vip.getId())
                    .update();
        }else {
            final DateTime now = DateUtil.date();
            expireTime = now.offset(DateField.DAY_OF_YEAR, vip.getAvailableMonth());
            JaMemberVip memberVip = new JaMemberVip();
            if (vipInfo.getIfVip() == 2) {
                memberVip.setId(vipInfo.getMemberVipId());
            }
            memberVip.setMemberId(memberId);
            memberVip.setCreateTime(DateUtil.now());
            if (now.dayOfMonth() == 29) {
                memberVip.setPushTime(28);
            }else if (now.dayOfMonth() == 31){
                memberVip.setPushTime(30);
            } else {
                memberVip.setPushTime(DateUtil.dayOfMonth(now));
            }
            memberVip.setLevel(vip.getLevel());
            memberVip.setVipInfoId(vip.getId());
            memberVip.setExpireTime(expireTime.toString());
            saveOrUpdate(memberVip);
        }
        if (vip.getLevel() > 1) {
            final List<JaCoupon> list = couponService.lambdaQuery().eq(JaCoupon::getSource, 2).list();
            if (list.size() > 0) {
//            查看本月是否已经发放会员券
                final Long hasList = memberCouponsService.lambdaQuery()
                        .eq(JaMemberCoupons::getCouponsId, list.stream().map(JaCoupon::getId).collect(Collectors.toList()))
                        .eq(JaMemberCoupons::getMemberId, memberId)
                        .like(JaMemberCoupons::getCreateTime, DateUtil.today().substring(0, 7))
                        .count();
                if (hasList == 0) {
                    logger.info("开通会员发放优惠券：" + memberId + "-" + JSON.toJSONString(list));
                    for (JaCoupon coupon : list) {
                        memberCouponsService.addCoupons(coupon.getId(), coupon.getNum(), memberId);
                    }
                }else {
                    logger.info("续费不重复发放");
                }
            }
        }
    }

    public static void main(String[] args) {
        System.err.println(DateUtil.date().offset(DateField.DAY_OF_YEAR, 365));
    }
}
